<template>
	<el-dialog :title="group.id ? '修改分类' : '新增分类'" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
		<!-- 填写分类信息 -->
		<el-input v-model="form.name" placeholder="请输入分类名称" maxlength="16"></el-input>
		<span slot="footer" class="dialog-footer">
			<el-button @click="handleClose">取消</el-button>
			<el-button type="primary" @click="handleConfirm">确定</el-button>
		</span>
	</el-dialog>
</template>
<script>
import { createKnowledgeBaseCategory, updateKnowledgeBaseCategory } from '@/api/api';
export default {
	props: {
		visible: {
			type: Boolean,
			default: false
		},
		group: {
			type: Object,
			default: () => ({})
		},
		parentId: {
			type: Number,
			default: 0
		}
	},
	data() {
		return {
			dialogVisible: false,
			form: {
				name: ''
			}
		};
	},
	mounted() {
		this.dialogVisible = this.visible;
		this.form.name = this.group.name || '';
	},
	methods: {
		handleClose() {
			this.dialogVisible = false;
			this.$emit('close');
		},
		handleConfirm() {
			console.log(this.form);
			if (!this.form.name.trim()) {
				this.$message.error('请输入分类名称');
				return;
			}
			if (this.group.id) {
				this.update();
			} else {
				this.create();
			}
		},
		// 新增分类
		create() {
			// {name:分类名称, parentId:0}
			createKnowledgeBaseCategory({name: this.form.name.trim(), parentId: this.parentId})
				.then(res => {
					console.log(res.data);
					const {code, data} = res.data;
					if (code === 200 && data) {
						this.dialogVisible = false;
						this.$emit('confirm', data);
					} else {
						this.$message.error('新增分类失败，请稍后再试');
					}
				})
				.catch(err => {
					console.error(err);
					if (err.code === 6014) {
						this.$message.error('该分类下已存在问题，不允许创建分类');
						this.handleClose();
					} else if (err.code === 1002) {
						this.$message.error('分类名已存在');
					} else {
						this.$message.error('新增分类失败，请稍后再试');
					}
				});
		},
		// 编辑分类
		update() {
			updateKnowledgeBaseCategory(this.group.id, this.form.name)
				.then(res => {
					console.log(res);
					if (res.data.code === 200) {
						this.dialogVisible = false;
						this.$emit('edit-name', {...this.group, name: this.form.name.trim()});
					} else {
						this.$message.error('修改分类失败，请稍后再试');
					}
				})
				.catch(err => {
					console.error(err);
					this.$message.error('修改分类失败，请稍后再试');
				});
		}
	}
};
</script>
<style scoped lang="less"></style>
